import { defineStore } from "pinia";
import { store } from "@/store";

interface UserState {
  menus: MenuType[];
}

export const useUserStore = defineStore("user", {
  state(): UserState {
    return {
      menus: [],
    };
  },
  getters: {
    getMenusConf(state) {
      const newMenus: { [key: number]: MenuType } = {};
      state.menus.forEach((menu) => {
        if (menu.parentId === 0) {
          //一级权限对象
          //newMenus.push(menu)
          newMenus[menu.id] = {
            ...menu,
            children: newMenus[menu.id]?.children,
          };
        } else {
          //二级权限对象
          // menu.parentId; //对应的一级id
          newMenus[menu.parentId] ??= {} as MenuType;
          newMenus[menu.parentId].children ??= [];
          newMenus[menu.parentId].children?.push(menu);
        }
      });
      return newMenus;
    },
  },
  actions: {
    updateMenus(menus: MenuType[]) {
      this.menus = menus;
    },
  },
});

export const useUserStoreWithOut = () => useUserStore(store);
